<template>
	<!-- pages/orders/orders.wxml -->
	<view class="orders">
		<view class="orders_area" @tap="toSelectAddress">
			<view class="area_left">
				<image class="area_img" src="/static/pages/image/location.png"></image>
				<view class="area_content" v-if="default_address.id">
					<view class="area_head">
						<text class="area_name">{{default_address.nickname}}</text>
						<text class="area_phone">{{default_address.phone}}</text>
					</view>
					<text class="area_txt">{{default_address.area}}</text>
				</view>
				<view class="no_area" v-else>
					<text class="area_name">还没有选择地址哦！</text>
				</view>
			</view>
			<image class="area_right" src="/static/pages/image/area_right.png"></image>
		</view>
		
		<view class="commodity_list">
			<view class="commodity_item" v-for="(item,index) in params" :key="index">
				<view class="commodity_info">
					<image class="commodity_img" :src="getImages(item.details.image)"></image>
					<view class="commodity_content">
						<text class="commodity_title">{{item.details.title}}</text>
						<view class="commodity_money">
							<text class="money_symbol">¥</text>
							<text class="money_txt">{{filter.getPriceIntegr(item.parm.param_price)}}</text>
							<text class="money_decimal">.{{filter.getPriceDecimals(item.parm.param_price)}}</text>
						</view>
						<text class="commodity_title">{{item.parm.name}}</text>
						<view class="buy_num">
							<text class="num_txt">购买数量</text>
							<view class="count_num">
								<view class="count_minus" @tap="onMinus(item)">
									<image class="minus_img" src="/static/pages/image/minus.png"></image>
								</view>
								<input class="num" :value="item.sum" type="number" @input="handleInput">
								<view class="count_add" @tap="onAdd(item)">
									<image class="add_img" src="/static/pages/image/add.png"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="commodity_moneyNum">
					<text class="moneyNum_title">商品金额</text>
					<view class="moneyNum_content">
						<text class="money_symbol">¥</text>
						<text class="money_txt">{{filter.getPriceIntegr(item.total_money)}}</text>
						<text class="money_decimal">.{{filter.getPriceDecimals(item.total_money)}}</text>
					</view>
				</view>
			</view>
		</view>
		

		<view class="commodity_pay">
			<view v-for="(item, index) in pay_list" :key="index" class="pay_item" :data-id="item.id" @tap="onChangePay">
				<view class="item_left">
					<image v-if="item.id == 1" class="wx_img" src="/static/pages/image/wx_img.png"></image>
					<image v-if="item.id == 2" class="balance_img" src="/static/pages/image/balance_img.png"></image>
					<text class="item_txt">{{item.lab}}</text>
				</view>
				<image v-if="item.id == isActive" class="right_img" src="/static/pages/image/chcked.png"></image>
				<view v-else class="right_round"></view>
			</view>
		</view>

		<view class="footer">
			<view class="footer_money">
				<text class="money_symbol">¥</text>
				<text class="money_txt">{{filter.getPriceIntegr(total_money)}}</text>
				<text class="money_decimal">.{{filter.getPriceDecimals(total_money)}}</text>
			</view>

			<button class="footer_buttom" @tap="onSubmitOrder">立即购买</button>
		</view>
	</view>
</template>

<script module="filter" lang="wxs" src="../../we7/resource/js/tools.wxs"></script>

<script>
	// pages/orders/orders.js
	var app = getApp();

	export default {
		data() {
			return {
				isActive: 1,
				money: 0,
				number: 1,
				total_money: 0,
				default_address: {},
				pay_list: [{
					lab: '微信支付',
					id: 1
				}, {
					lab: '余额支付',
					id: 2
				}],
				isShopping:false,
				params:[]
			};
		},

		components: {},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.params = JSON.parse(options.parmas);
			console.log(this.params)
			this.isShopping = options.type == 1 ? true : false
			this.countTotalMoney()
			// let details = JSON.parse(options.details);
			// this.parm = JSON.parse(options.parm)
			// this.sum = options.sum
			// this.setData({
			// 	details: details,
			// 	money: details.sell_price,
			// 	total_money: this.parm.param_price
			// });
			// this.details.sum = this.details.sum ? this.details.sum : 1
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			if (wx.getStorageSync('currentSelectId')) {
				this.getSelectAddress();
			} else {
				this.getDefaultAddress();
			}
		},

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			getImages(images){
				let str = ''
				if(images){
					str = JSON.parse(images)[0]
				} 
				return str
			},
			countTotalMoney(){
				let nums = this.params.map(item=> Number(item.total_money))
				this.total_money = this.sum(nums)
			},
			sum(arr) {
			    let num = arr.reduce(function(prev, curr, idx, arr){
			        return prev + curr;
			    });
				return num.toFixed(2)
			},
			onSetTotal(item) {
				item.total_money = ( item.sum * item.parm.param_price).toFixed(2)
				this.countTotalMoney()
				this.$forceUpdate()
			},
			onMinus(item) {
				if (item.sum <= 1) return;
				item.sum = Number(item.sum) - 1
				this.onSetTotal(item);
			},

			onAdd(item) {
				item.sum = Number(item.sum) + 1
				this.onSetTotal(item);
			},

			toSelectAddress() {
				wx.navigateTo({
					url: '/pagesA/selectAddress/selectAddress'
				});
			},

			// 改变支付方式
			onChangePay(event) {
				const id = event.currentTarget.dataset['id'];
				this.setData({
					isActive: id
				});
			},

			onSubmitOrder() {
				if (!this.default_address.id) {
					wx.showToast({
						title: '请选择地址',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				let order = []
				this.params.forEach(item=>{
					order.push({
						id:this.isShopping ? item.details.goods_id : item.details.id,
						member_receipt_id: this.default_address.id,
						sum:item.sum,
						parm:item.parm.param_id
					})
				})
				wx.showLoading({
					title: '加载中'
				});
				app.globalData.util.request({
					url: "entry/wxapp/Api",
					data: {
						m: "monai_market",
						r: "goods.order.add",
						type: this.isActive,
						uid: wx.getStorageSync('uid'),
						order:JSON.stringify(order)
					},
					success: res => {
						if (this.isActive == 1) {
							this.wx_pay(res.data)
						} else {
							this.pay_succeed()
						}
					},
					fail: res => {
						wx.showToast({
							title: res.data.message,
							icon: 'none',
							duration: 2000
						});
						wx.hideLoading();
					}
				});
			},
			wx_pay(params) {
				wx.requestPayment({
					timeStamp: params.data.timeStamp,
					nonceStr: params.data.nonceStr,
					package: params.data.package,
					signType: params.data.signType,
					paySign: params.data.paySign,
					success:(result)=> {
						this.pay_succeed()
					},
					fail(err) {
						wx.showToast({
							title: '支付失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			pay_succeed() {
				wx.showToast({
					title: '支付成功',
					icon: 'none',
					duration: 2000
				}); // 购买成功清除选择的地址 下次使用默认

				wx.removeStorageSync('currentSelectId');
				setTimeout(() => {
					wx.navigateTo({
						url: '/pagesA/myOrders/myOrders'
					});
				}, 1000);
				wx.hideLoading();
			},
			getDefaultAddress() {
				wx.showLoading({
					title: '加载中'
				});
				app.globalData.util.request({
					url: "entry/wxapp/Api",
					data: {
						m: "monai_market",
						r: "member.index.moreceipt",
						uid: wx.getStorageSync('uid')
					},
					success: res => {
						this.setData({
							default_address: res.data.data
						});
						wx.hideLoading();
					},
					fail: res => {
						wx.hideLoading();
					}
				});
			},

			getSelectAddress() {
				wx.showLoading({
					title: '加载中'
				});
				app.globalData.util.request({
					url: "entry/wxapp/Api",
					data: {
						m: "monai_market",
						r: "member.index.receipt_detail",
						uid: wx.getStorageSync('uid'),
						id: wx.getStorageSync('currentSelectId')
					},
					success: res => {
						this.setData({
							default_address: res.data.data
						});
						wx.hideLoading();
					},
					fail: res => {
						wx.hideLoading();
					}
				});
			},

			handleInput() {
				console.log("占位：函数 handleInput 未声明");
			}

		}
	};
</script>
<style>
	@import "./orders.css";
</style>
